package com.tiny.tinyweb.core.jsf;

import java.util.Arrays;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tiny.tinyweb.core.dao.entity.MapEntity;
import com.tiny.tinyweb.core.log.LogInfo;
import com.tiny.tinyweb.core.utils.FacesUtils;
import com.tiny.tinyweb.core.utils.ReflectionUtils;

public class FacesLogListener implements PhaseListener {
    private static final long serialVersionUID = 1L;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void beforePhase(PhaseEvent event) {
        FacesContext context = event.getFacesContext();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        HttpSession session = request.getSession(false);
        Map<String, String[]> params = request.getParameterMap();

        String forward = (String) ReflectionUtils.getPropertyValue(request, "requestDispatcherPath");
        String sessionID = session == null ? null : session.getId();
        String captured = Arrays.toString(params.get("ice.event.captured")).replaceAll("\\[", "").replaceAll("\\]", "");
        String type = Arrays.toString(params.get("ice.event.type")).replaceAll("\\[", "").replaceAll("\\]", "");
        String bean = Arrays.toString(params.get("bean")).replaceAll("\\[", "").replaceAll("\\]", "");

        MapEntity userInfo = (MapEntity) FacesUtils.getSessionUser();
        LogInfo logInfo = new LogInfo();
        logInfo.setOperation(captured);
        if (userInfo != null && userInfo.get("userNo") != null) {
            logInfo.setOperatorID((String) userInfo.get("userNo"));
        }
        logInfo.setOperatorIP(FacesUtils.getIpAddr(request));
        logInfo.setSessionID(sessionID);
        logInfo.setMessage(String.format("event type[%1$s], forward to[%2$s], bean name[%3$s]", type, forward, bean));
        logger.trace(logInfo.toString());
    }

    @Override
    public void afterPhase(PhaseEvent event) {
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}
